import { defineStore } from 'pinia';

export const pageTagStore = defineStore('pageTagStore', {
    state: () => ({
        pageTags: [],
        pageTagActive:''
    }),

    getters:{},

    actions: {
        addTag(tagData) {
            let result = this.pageTags.find(item => {
                return item.path === tagData.path;
            });
            if(!result) {
                this.pageTags.push(tagData);
                this.pageTagActive = tagData.path;
            };
        },

        deleteTag(data) {
            let tags = this.pageTags;
            this.pageTags = tags.filter(item => item.path !== data.path);
            let activeName = this.pageTagActive;
            if(activeName == data.path) {
                tags.forEach( (item, index) => {
                    if(item.path === data.path) {
                        // 找离当前标签最近的标签
                        const nextTag = tags[index + 1] || tags[index - 1];
                        // 如果nextTab存在就赋值,也就是如果右边没有就取左边的
                        nextTag && (activeName = nextTag.path);
                    } ;
                });
                this.pageTagActive = activeName;
            };
        }
    },

    persist:[
        {
            paths: ['pageTags'],
            storage: sessionStorage,
        },
    ]
})